const common = require('../../utils/common');
const TenPay = require('tenpay');
const config = require('../../config/pay');
const api = new TenPay(config);
class Pay {
    /**
     * 返回签名
     * @api {POST}        /pay/sign     返回签名
     * @apiName           /pay/sign
     * @apiGroup          Pay
     * @apiParam          {Int}          id           id
     * @apiParam          {String}       group=1       会员or次卡(1 会员 2次卡)
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
             "appId": "wx7cd2a45df18747f6",
            "timeStamp": "1560476142",
            "nonceStr": "H9SMO5aJ9RGuQOxH",
            "package": "prepay_id=wx14093531183884cc0fd2e9441405589800",
            "signType": "MD5",
            "paySign": "5535965A5D80C5292E33DC067E9935F7",
            "timestamp": "1560476142"
         }
       }
     */
    async sign(ctx) {
        const {
            db,
            user: { User },
            request: {
                body: { id, group }
            }
        } = ctx;

        // 查询信息、生成订单
        let data;
        const orderNo = await common.randomNo(8);
        let open = await db.User.findOne({ where: { id: User.id } });

        if (parseInt(group) === 1) {
            data = await db.Members.findOne({ where: { id: id } });
        } else {
            data = await db.TimeCard.findOne({ where: { id: id } });
        }

        // 存储订单信息
        let par = {
            orderId: orderNo,
            userId: User.id,
            group: group,
            goodId: id,
            desc: data.desc,
            amount: data.actualPrice
        };
        db.Order.upsert(par);

        // 生成支付订单信息
        let pars = {
            out_trade_no: orderNo,
            body: data.desc,
            total_fee: data.actualPrice * 100,
            openid: open.openId
        };

        if (User.id === 38) {
            pars.total_fee = 1;
        } else if (User.id === 37) {
            pars.total_fee = 1;
        }

        let result = await api.getPayParams(pars);

        ctx.success(result);
    }
    /**
     * 支付回调
     * @api {POST}        /pay/notify     支付回调
     * @apiName           /pay/notify
     * @apiGroup          Pay
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "SUCCESS"
       }
     */
    async notify(ctx) {
        const {
            db,
            model,
            request: {
                body: { xml }
            }
        } = ctx;
        console.log('微信回调', xml);
        let data;
        const resultCode = xml.result_code[0];

        if (xml.result_code.length <= 0) {
            console.log('回调没有数据');
            ctx.body = 'FAIL';
            return;
        }

        const orderId = xml.out_trade_no[0];
        if (resultCode === 'SUCCESS') {
            // 查询订单信息
            let order = await db.Order.findOne({ where: { orderId: orderId } });

            if (!order) {
                ctx.body = 'FAIL';
                return;
            } else {
                if (order.group === 1) {
                    // 会员卡
                    data = await db.Members.findOne({
                        where: { id: order.goodId }
                    });
                    // 儿子信息
                    let user = await db.User.findOne({
                        where: { id: order.userId }
                    });
                    // 爸爸信息
                    let parent = await db.User.findOne({
                        where: { id: user.parentId }
                    });
                    // 更新用户
                    // 插入数据、启动事务
                    let transaction;
                    try {
                        transaction = await model.transaction();

                        let parse = {
                            memberId: order.goodId,
                            leftDay: data.day * 86400,
                            buyMemberTime: Math.round(new Date() / 1000),
                            endMemberTime:
                                Math.round(new Date() / 1000) +
                                data.day * 86400,
                            member: order.amount,
                            isMember: 1
                        };

                        if (user.memberId !== 0) {
                            parse.leftDay = data.day * 86400 + user.leftDay;
                            parse.endMemberTime =
                                user.endMemberTime + data.day * 86400;
                            parse.member =
                                parseInt(order.amount) + parseInt(user.member);
                        }
                        console.log('购买会员', parse);

                        await db.User.update(parse, {
                            where: { id: order.userId }
                        });

                        // 爸爸增加会员
                        if (parent) {
                            const reward = await db.Giving.findOne({
                                where: { type: 1 }
                            });
                            const day = reward.day * 86400;
                            // 判断是否购买会员
                            if (parent.memberId === 0) {
                                // 如果没购买，直接增加会员
                                parent.leftDay = day;
                                parent.buyMemberTime = Math.round(
                                    new Date() / 1000
                                );
                                parent.endMemberTime =
                                    Math.round(new Date() / 1000) + day;
                            } else {
                                parent.leftDay = parent.leftDay + day;
                                parent.endMemberTime =
                                    parent.endMemberTime + day;
                            }
                            // 记录
                            await db.Reward.upsert({
                                userId: user.id,
                                givingId: parent.id,
                                day: reward.day,
                                limit: 0,
                                isShop: 1
                            });
                            parent.save();
                        }
                        // 购买记录
                        await db.Buy.upsert({
                            userId: user.id,
                            price: order.amount,
                            type: order.desc,
                            status: 1
                        });
                        // 提交事务
                        await transaction.commit();
                        ctx.body = 'SUCCESS';
                        return;
                    } catch (e) {
                        console.log(e);
                        // 回滚
                        await transaction.rollback();
                        ctx.body = 'FAIL';
                        return;
                    }
                } else {
                    // 次卡
                    data = await db.TimeCard.findOne({
                        where: { id: order.goodId }
                    });

                    // 更新用户
                    let user = await db.User.findOne({
                        where: { id: order.userId }
                    });
                    let transaction;
                    try {
                        transaction = await model.transaction();

                        let res = {
                            cardTimeId: order.goodId,
                            limit: user.limit + data.limit,
                            endCardTime:
                                Math.round(new Date() / 1000) +
                                data.effective * 86400,
                            cardTime:
                                parseInt(order.amount) +
                                parseInt(user.cardTime),
                            isTimeCard: 1
                        };

                        if (!user.buyCardTime) {
                            // 如果不存在购买
                            res.buyCardTime = Math.round(new Date() / 1000);
                        }

                        if (user.endCardTime) {
                            // 如果存在购买
                            res.endCardTime =
                                user.endCardTime + data.effective * 86400;
                        }

                        await db.User.update(res, {
                            where: { id: order.userId }
                        });

                        // 购买记录
                        await db.Buy.upsert({
                            userId: user.id,
                            price: order.amount,
                            type: order.desc,
                            status: 0
                        });

                        await transaction.commit();
                        ctx.body = 'SUCCESS';
                    } catch (e) {
                        console.log(e);
                        // 回滚
                        await transaction.rollback();
                        ctx.body = 'FAIL';
                        return;
                    }
                }
            }
        } else {
            // 后续添加退款功能
            ctx.body = 'FAIL';
        }
    }
}
module.exports = new Pay();
